<template>
  <div>
    <el-row :gutter="10" center class="monitor">
      <div class="backBeforepage">
        <el-button type="text" icon="el-icon-caret-left" @click="prev">上一页</el-button>
      </div>
      <el-col :span="6" :offset="1">物理位置监控可视化操作界面</el-col>
      <el-col :span="8" :offset="2">新增房间</el-col>
    </el-row>
    <el-card>
      <el-form size="mini" ref="form1" :model="roomForm" :rules="rules" label-width="140px" label-position="left">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="roomName" label="房间名称">
              <el-input v-model="roomForm.roomName" placeholder="请输入房间名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="stationSize" label="座位数">
              <el-input-number v-model="roomForm.stationSize" :min="1" placeholder="请输入工位数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="IMAGENO" label="图片号">
              <el-input v-model="roomForm.IMAGENO" placeholder="请输入图片号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="IMAGENAME" label="图片名字">
              <el-input v-model="roomForm.IMAGENAME" placeholder="请输入图片名字"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item prop="URL" label="图片">
              <el-col :span="6">
                <el-upload class="avatar-uploader" :action="fileUploadUrl" :show-file-list="false"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-col>
              <el-col :span="6" :offset="2" v-if="roomForm.URL!=''">
                <el-image style="width: 100px; height: 100px" :src="roomForm.URL" fit="cover"></el-image>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item prop="IMAGEDESC" label="图片描述">
              <el-input v-model="roomForm.IMAGEDESC"  placeholder="请输入图片描述"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="REMARK1" label="备注1">
              <el-input v-model="roomForm.REMARK1" type="textarea" :rows="2" placeholder="请输入备注1 "></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="REMARK2" label="备注2">
              <el-input v-model="roomForm.REMARK2" type="textarea" :rows="2" placeholder="请输入备注2"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="addBkImg">新增底图</el-button>
          </el-col> -->
        </el-row>
        <el-row :gutter="10">

          <el-col :span="8" :offset="2">
            <el-button size="mini" type="success" icon="el-icon-plus" @click="createRoom">创建房间</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card v-model="visible" v-show="visible" style="margin-top:10px;height:1200px;">
      <el-form size="mini" ref="form2" :model="stationForm" :rules="rules" label-width="140px" label-position="left">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item prop="stationNo" label="工位号：">
              <el-input v-model="stationForm.stationNo" placeholder="请输入工位号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="stationIp" label="工位IP：">
              <el-input v-model="stationForm.stationIp" placeholder="请输入工位IP"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button size="mini" type="primary" @click="createStation">创建工位</el-button>
          </el-col>
          <el-col :span="8">
            <el-button size="mini" type="success" icon="el-icon-plus" @click="assembleRoomInfo">组装房间信息</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-container>
        <el-header height="30px" class="physical_title">
          <el-dialog title="操作" width="300px" :modal="false" :center="true" :visible.sync="dialogVisible">
            <el-row class="dialogRow">
              <el-col>工位信息</el-col>
            </el-row>
            <el-row>
              <el-col :span="6">工位号：</el-col>
              <el-col :span="6">
                <el-tag size="mini">{{ dialogForm.seatNo }}</el-tag>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">工位IP：</el-col>
              <el-col :span="6">
                <el-tag size="mini">{{ dialogForm.seatIp }}</el-tag>
              </el-col>
            </el-row>
            <el-row class="dialogRow">
              <el-col>坐标调整</el-col>
            </el-row>
            <el-row>
              <el-col :span="6">横坐标：</el-col>
              <el-col :span="18">
                <el-input-number size="mini" v-model="dialogForm.left" @change="changeSeatLeft"></el-input-number>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">纵坐标：</el-col>
              <el-col :span="18">
                <el-input-number size="mini" v-model="dialogForm.top" @change="changeSeatTop"></el-input-number>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <div class="grid-content bg-purple"></div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light"></div>
              </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
              <el-button size="mini" @click="dialogVisible = false">确定</el-button>
              <el-button type="primary" size="mini" @click="delateStation">删除工位</el-button>
            </span>
          </el-dialog>
        </el-header>
        <el-container>
          <el-aside class="physical_left" width="1500px" height="813px">
            <el-col>
              <div>
                <canvas id="canvas" width="1500px" height="813px" style="border:1px solid black"></canvas>
              </div>
            </el-col>
          </el-aside>
        </el-container>
      </el-container>
    </el-card>
  </div>
</template>

<script>
  // 全局的参数
  import getGlobalParams from "@/common/utils/getGlobalParams";
  // 底图信息查询
  import queryBackgroundImage from "@/message/siteManagement/workplacemonitoring/queryBackgroundImage";
  // 房间基本信息
  import queryRoomInfo from "@/message/siteManagement/workplacemonitoring/queryRoomInfo";
  // 房间状态信息
  import queryRoomSeatStatus from "@/message/siteManagement/workplacemonitoring/queryRoomSeatStatus";
  // YYGL
  import requestYg from "@/common/utils/requestYg";

  import {
    fabric
  } from "fabric";
  export default {
    name: "",
    data() {
      return {
        // 后端可能会传的数据
        canvasObj: {},
        btnFlag: true,
        fileUploadUrl:'',
        roomForm: {
          IMAGENO: '',
          IMAGENAME: '',
          IMAGEDESC: '',
          URL: '',
          REMARK1: '',
          REMARK2: '',
          roomName: "",
          stationSize: null,
          bkImageUrl: "",
          stationList: [],
          stationListString: ""
        },
        changeBkImg: [],
        rules: {
          roomName: [{
            required: true,
            message: "房间名称必填",
            trigger: "blur"
          }],
          stationSize: [{
            required: true,
            message: "工位数必填",
            trigger: "blur"
          }],
          bkImageUrl: [{
            required: true,
            message: "cad底图必选",
            trigger: "blur"
          }],
          stationNo: [{
            required: true,
            message: "工位号必填",
            trigger: "blur"
          }],
          stationIp: [{
            required: true,
            message: "工位号必填",
            trigger: "blur"
          }]
        },
        tableData: [],
        bkImageUrlList: [],

        stationForm: {
          stationNo: "",
          stationIp: ""
        },
        // 工位号
        stationMap: new Map(),
        // 工位IP
        stationIpMap: new Map(),

        visible: false,
        room: {},
        // 对话框
        dialogVisible: false,
        dialogForm: {
          seatNo: "",
          left: 0,
          top: 0,
          seatIp: ""
        }
      };
    },
    computed: {},
    created: function () {},
    watch: {},
    mounted() {
      // console.log("新增房间,mounted");
      //底图下拉框选项；
      // this.query();
            this.fileUploadUrl = getGlobalParams.get("ImgUploadAddress");

    },

    methods: {
        handleAvatarSuccess(res, file) {
        this.roomForm.URL = getGlobalParams.get("ImgDownloadAddress") + '/' + file.name
        console.log(this.roomForm.URL)
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      // 远程请求图片数据
      async query() {
        let resBody = new queryBackgroundImage();
        (resBody.data.pageflag = ""), (resBody.data.IMAGEDESC = ""); //文字描述
        resBody.data.IMAGENO = ""; //图片号
        resBody.data.IMAGENAME = ""; //图片名
        console.log("底图query的resBody.data", resBody.data);
        requestYg(resBody)
          .then(response => {
            console.log("底图信息查询的response，", response);

            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.tableData = response.RSP_BODY.Result || [];
              console.log("tableData,", this.tableData);
              //这里的地址在globalParams中配置  需要和后台的存放文件的配置统一
              //在这里只取图片下行地址中的ip地址
              //在表格中返回的内容只有相对地址，所以需要使用ip地址拼接
              var IpAddress = getGlobalParams.get(
                "WorkPlaceMonitorBackgroundImgDownloadUrl"
              );
              console.log("IpAddress,", IpAddress);
              //  console.log("scope.row.IMAGENAME,",scope.row.IMAGENAME);
              // var Url =IpAddress+scope.row.IMAGENAME;
              this.bkImageUrlList = this.tableData.map(item => {
                console.log("mounted的map中的item", item);
                return {
                  value: IpAddress + item.IMAGENAME,
                  name: item.IMAGEDESC,
                  imgName: item.IMAGENAME,
                  Url: item.URL
                };
              });
              console.log("this.bkImageUrlList:", this.bkImageUrlList);
            } else {
              this.$message({
                type: "error",
                message: response.SYS_HEAD.ReturnMessage
              });
              this.tableData = [];
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
          });
      },
      // 点击 创建房间按钮
      createRoom() {
        // 所有输入必须有值
        this.$refs["form1"].validate(valid => {
          console.log("form1.volid,", valid);
          if (valid) {
            console.log("创建房间取用的roomForm,", this.roomForm);
            // 创建房间前先清除canvas画布
            var canvas = null;
            if (this.canvasObj.clear) {
              canvas = this.canvasObj;
              canvas.clear();
            } else {
              canvas = this.canvasObj = new fabric.Canvas("canvas");
            }
            // 显示画布
            this.visible = true;
            // 数据重置
            this.stationMap = new Map();
            // 工位IP
            this.stationIpMap = new Map();
            // 去除交互
            canvas.interactive = false;
            // 创建房间CAD底图
            fabric.Image.fromURL(this.roomForm.bkImageUrl, function (oImg) {
              // 设置不可选择
              oImg.selectable = false;
              canvas.add(oImg);
            });
          } else {
            this.$message({
              type: "warning",
              message: "房间信息必须填写完整！"
            });
            return false;
          }
        });
        console.log("创建房间后的canvasObj,", this.canvasObj);
      },

      // 点击创建工位按钮
      createStation() {
        console.log("创建工位前canvasObj,", this.canvasObj);

        // 判断工位编号 是否存在
        if (!this.stationForm.stationNo) {
          this.$message({
            type: "error",
            message: "工位不存在，请重新输入！"
          });
          return;
        }
        // 判断工位IP 是否存在
        if (!this.stationForm.stationIp) {
          this.$message({
            type: "error",
            message: "工位IP不存在，请重新输入！"
          });
          return;
        }

        // 获取工位编号
        const stationNo = this.stationForm.stationNo;
        // 获取工位Ip
        const stationIp = this.stationForm.stationIp;
        // 判断工位IP是否存在
        if (this.stationIpMap.get(stationIp)) {
          this.$message({
            type: "error",
            message: "工位IP已存在，请重新输入！"
          });
          return;
        }
        // 判断工位编号是否存在
        if (this.stationMap.get(stationNo)) {
          this.$message({
            type: "error",
            message: "工位已存在，请重新输入！"
          });
          return;
        }

        // 判断工位是否超过原先设定工位数;
        const mapLen = this.stationMap.size;
        const stationLen = parseInt(this.roomForm.stationSize);
        console.log("mapLen,", mapLen);
        console.log("stationLen,", stationLen);

        if (mapLen == stationLen) {
          this.$message({
            type: "error",
            message: "创建房间【工位数】：( " +
              mapLen +
              " )  等于 ( " +
              stationLen +
              " )  请【增加工位数】或者【组装房间信息】"
          });
          return;
        }
        if (mapLen > stationLen) {
          this.$message({
            type: "error",
            message: "创建房间【工位数】：( " +
              mapLen +
              " )  多于 ( " +
              stationLen +
              " )  请【删除工位】或者【增加工位数】"
          });
          return;
        }
        // 创建工位
        // 设置工位初始信息
        const station = {
          stationNo,
          stationIp, //工位Ip,
          initStatusNo: "23", // 初始状态码都是23， 名称是未登录
          initStatusName: "未登录",
          initIconUrl: "static/images/icons/icon/man-in.png", // 初始图标URL,都是未登录图标
          left: 0,
          top: 0
        };
        // 设置工位方块图默认属性
        const seatWidth = 50;
        const seatHeight = 50;
        const fontSize = 8;
        const _this = this;
        // 画工位方块图
        fabric.Image.fromURL(station.initIconUrl, function (initIconImage) {
          // 设置小图标
          initIconImage = initIconImage.scale(0.6).set({
            left: station.left + 14,
            top: station.top + 2
          });

          // 绘制矩形
          var body = new fabric.Rect({
            width: seatWidth,
            height: seatHeight,
            left: station.left,
            top: station.top,
            fill: " gray",
            rx: 10,
            ry: 10
          });
          // console.log("station,",station);

          // 工位号
          var seatNo = new fabric.Text(station.stationNo, {
            fontSize: 6,
            fill: "white",
            originX: "center",
            originY: "center",
            top: station.top + 31,
            left: station.left + 20
          });
          // 状态名称
          var statusName = new fabric.Text(station.initStatusName, {
            fontSize: fontSize,
            fill: "white",
            originX: "center",
            originY: "center",
            top: station.top + 43,
            left: station.left + 20
          });

          // 组合图片，
          var seatGroup = new fabric.Group(
            [body, seatNo, statusName, initIconImage], {
              // 给每个seatGroup对应唯一的工位对象;
              station: station,
              // 锁住X,Y方向，不可缩放
              lockScalingX: true,
              lockScalingY: true
            }
          );

          // 每个工位方块添加弹窗事件
          seatGroup.on("mouseup", function () {
            console.log(
              "UP:left:",
              parseInt(seatGroup.left),
              ",top:",
              parseInt(seatGroup.top)
            );

            _this.dialogForm.seatNo = station.stationNo;
            _this.dialogForm.seatIp = station.stationIp;

            _this.dialogForm.left = parseInt(seatGroup.left);
            _this.dialogForm.top = parseInt(seatGroup.top);
            _this.dialogVisible = true;
            console.log("UP:canvasObj,", _this.canvasObj);
            console.log("UP:seatGroup,", seatGroup);
          });

          console.log("add的SeatGroup,", seatGroup);

          _this.canvasObj.add(seatGroup);
          _this.canvasObj.renderAll();
          _this.stationMap.set(stationNo, seatGroup);
          _this.stationIpMap.set(stationIp, stationNo);
        });
        console.log("创建工位后的this.stationMap,", this.stationMap);
        console.log("创建工位后的this.stationIpMap,", this.stationIpMap);

        console.log("创建工位后的this.canvas,", this.canvasObj);
      },

      // 点击 组装房间信息事件
      assembleRoomInfo() {
        // 判断工位是否过少或过多
        const mapLen = this.stationMap.size;
        const stationLen = parseInt(this.roomForm.stationSize);
        if (mapLen < stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  少于( " +
              stationLen +
              " )  请继续【创建工位】或者【减少工位数】！"
          });
          return;
        }
        if (mapLen > stationLen) {
          this.$message({
            type: "error",
            message: "已创建【工位数】：( " +
              mapLen +
              " )  多于 ( " +
              stationLen +
              " )  请【删除工位】或者【增加工位数】！"
          });
          return;
        }
        // 组装房间信息

        // 组装工位信息
        console.log("forEach的stationMap,", this.stationMap);
        // 异步forEach,
        var _this = this;
        this.stationMap.forEach(function (stationImage, key) {
          console.log("ele的stationImage,", stationImage);
          let stationInfo = stationImage.station;
          // 注意left和top，必须是stationImage的，stationImage.station的left和top都是0；
          _this.roomForm.stationListString +=
            stationInfo.initIconUrl +
            "," +
            stationInfo.initStatusName +
            "," +
            stationInfo.initStatusNo +
            "," +
            stationInfo.stationNo +
            "," +
            stationImage.left +
            "," +
            stationImage.top +
            "," +
            stationInfo.stationIp +
            "|";
        });
        console.log("stationListString,", this.roomForm.stationListString);
        console.log("assembleRoomInfo,this.roomForm,", this.roomForm);
        this.addRoomInfo();
      },

      //改变底图下拉框选项
      handleChange(val) {
        console.log("handleChange,", val);
        console.log(this.bkImageUrlList);
        var bkImg = this.bkImageUrlList.filter(function (ele, index) {
          console.log(ele, index);
          return ele.value == val;
        });
        console.log("bkImg", bkImg);
        this.changeBkImg = bkImg;
      },
      // 改变横坐标
      changeSeatLeft() {
        const seatNo = this.dialogForm.seatNo;
        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.stationNo === seatNo;
        });
        const seat = filterSeat[0];
        seat.left = this.dialogForm.left;
        this.canvasObj.renderAll();
      },

      // 改变纵坐标
      changeSeatTop() {
        const seatNo = this.dialogForm.seatNo;
        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.stationNo === seatNo;
        });
        const seat = filterSeat[0];
        seat.top = this.dialogForm.top;
        this.canvasObj.renderAll();
      },

      //删除工位
      delateStation() {
        const seatNo = this.dialogForm.seatNo;
        const seatIp = this.dialogForm.seatIp;

        const filterSeat = this.canvasObj._objects.filter(function (item, index) {
          return item.station && item.station.stationNo === seatNo;
        });
        const seat = filterSeat[0];

        this.canvasObj.remove(seat);
        console.log("remove后的canvas,", this.canvasObj);
        this.stationMap.delete(seatNo);
        this.stationIpMap.delete(seatIp);

        console.log("删除后的stationMap,", this.stationMap);

        console.log("删除后的stationIpMap,", this.stationIpMap);

        this.canvasObj.renderAll();
        this.dialogVisible = false;
      },
      // 新增底图
      addBkImg() {
        console.log("新增底图");
        this.$router.push({
          name: "ImageAdd"
        });
      },
      prev() {
        console.log("返回上一页");
        this.$router.go(-1);
      },

      // 组装房间发送后台接口：房间信息+工位信息组合成字符串，
      addRoomInfo() {
        console.log("addRoomInfo的this.roomForm,", this.roomForm);
        console.log("addRoomInfo的this.changeBkImg,", this.changeBkImg);
        console.log("addRoomInfo的this.bkImageUrlList,", this.bkImageUrlList);
        let resBody = new queryRoomInfo();
        resBody.data.oper_type = "A";
        resBody.data.ROOMNAME = this.roomForm.roomName; //房间名称
        resBody.data.SEATNO = "" + this.roomForm.stationSize; //工位数
        resBody.data.URL = this.roomForm.bkImageUrl; //底图
        resBody.data.seatInfo = this.roomForm.stationListString; //工位信息字符串
        resBody.data.IMAGENAME = this.changeBkImg[0].imgName;
        resBody.data.IMAGEDESC = this.changeBkImg[0].name;
        resBody.data.REMARK1 = "";
        console.log("房间新增  发送resBady,", resBody.data);
        requestYg(resBody)
          .then(response => {
            console.log("房间新增 response，", response);
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.$message({
                type: "success",
                message: "新增房间信息成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: response.SYS_HEAD.ReturnMessage
              });
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
          });
      }
    }
  };

</script>


<style lang="scss" scoped>
  * {
    list-style-type: none;
  }

  li {
    font-size: 1px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    ;
    line-height: 100px;
    text-align: center;
  }
  .monitor {
    width: 100%;
    height: 35px;
    line-height: 35px;
    background-color: #f5f5f5;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
    color: #208cf0;
    padding: 0px 35px;
    text-align: center;
  }

  .physical_title {
    color: #208cf0;
    padding: 0;
    margin: 0;
    // border-bottom: 1px solid #e5e5e5;
    line-height: 30px;
    margin-bottom: 5px;
  }

  .backBeforepage {
    display: inline-block;
    left: 10px;
    position: absolute;
  }

  .search_right {
    margin-left: 5px;
  }

  .physical_left {
    position: relative;
    // background-color:rgba(255,255,255);
    height: 100%;
    width: 1095px;
  }

  .mapMainBorder {
    border: 1px solid red;
    background-color: #f0f0f0;
    width: 1095px;
    height: 413px;
  }

  .mapimgLeft {
    width: 38.35%;
    height: 100%;
    float: left;
  }

  .mapimgRight {
    width: 61.65%;
    height: 100%;
    float: left;
  }

  .selectTree {
    min-width: 150px;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .dialog-text {
    display: inline-block;
    width: 100%;
    text-align: center;
    color: red;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

  .el-card {
    width: 100%;
  }

  .el-form-item {
    margin-left: 30px;
  }

  .el-form-item1 {
    margin-left: 10px;
  }

  .box2-button {
    width: 80px;
  }

  .el-card {
    overflow: inherit;
  }

  .asideText {
    width: 100%;
    height: 35px;
    line-height: 33px;
    color: #409eff;
    text-align: center;
  }

  .dialogRow {
    margin-top: 20px;
  }

</style>
